package com.cryptape.cita_wallet.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.MapUtils;
import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction;
import com.cryptape.cita_wallet.CytonApplication;
import com.cryptape.cita_wallet.activity.transfer.GetBackTransferPresenter;
import com.cryptape.cita_wallet.activity.transfer.TransferView;
import com.cryptape.cita_wallet.bean.CurrencyPrice;
import com.cryptape.cita_wallet.constant.ConstantUtil;
import com.cryptape.cita_wallet.event.TransferPushEvent;
import com.cryptape.cita_wallet.item.Wallet;
import com.cryptape.cita_wallet.item.transaction.AppTransaction;
import com.cryptape.cita_wallet.net.common.BaseUrlUtils;
import com.cryptape.cita_wallet.net.common.NetWorkManager;
import com.cryptape.cita_wallet.net.common.RxSubscriber2;
import com.cryptape.cita_wallet.net.request.HttpRequestMode;
import com.cryptape.cita_wallet.net.response.BaseResponse;
import com.cryptape.cita_wallet.service.http.EthRpcService;
import com.cryptape.cita_wallet.service.http.TokenService;
import com.cryptape.cita_wallet.service.http.WalletService;
import com.cryptape.cita_wallet.util.AddressUtil;
import com.cryptape.cita_wallet.util.Blockies;
import com.cryptape.cita_wallet.util.CurrencyUtil;
import com.cryptape.cita_wallet.util.NumberUtil;
import com.cryptape.cita_wallet.util.RSAUtils;
import com.cryptape.cita_wallet.util.db.DBWalletUtil;
import com.cryptape.cita_wallet.util.ether.EtherUtil;
import com.cryptape.cita_wallet.util.permission.PermissionUtil;
import com.cryptape.cita_wallet.util.permission.RuntimeRationale;
import com.cryptape.cita_wallet.util.qrcode.CodeUtils;
import com.cryptape.cita_wallet.view.CompressEditText;
import com.cryptape.cita_wallet.view.TitleBar;
import com.cryptape.cita_wallet.view.button.CommonButton;
import com.cryptape.cita_wallet.view.dialog.TransferDialog;
import com.cryptape.cita_wallet.view.tool.CytonTextWatcher;
import com.mangoworld.android.R;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.utils.Convert;

import java.math.BigInteger;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.Subscriber;

/**
 * Created by dengming on 17/3/20.
 */

public class GetBackCoinActivity extends NBaseActivity implements TransferView {

    private static final int REQUEST_CODE_SCAN = 0x01;
    private static final int REQUEST_CODE_TRANSACTION = 0x02;
    public static final String EXTRA_TOKEN = "extra_token";
    public static final String EXTRA_ADDRESS = "extra_address";

    public static final String ATOKENBALANCE = "aTokenBalance";
    public static final String BTOKENBALANCE = "bTokenBalance";


    private GetBackTransferPresenter mPresenter;

    private TextView walletAddressText;
    private TextView walletNameText;
    private TextView feeValueText;
    private TextView balanceText;
    private TextView hmio_balance_text;
    private ImageView scanImage;
    private CompressEditText mCetReceiverAddress;
    private AppCompatEditText transferValueEdit;
    private AppCompatEditText transferValueEdit1;
    private CommonButton nextActionButton;
    private CircleImageView photoImage;
    private ProgressBar progressBar;

    private TitleBar titleBar;
    public TransferDialog transferDialog;
    private AppTransaction mAppTransaction = new AppTransaction();
    private TextView lock_type;
    private RelativeLayout rl_deposit_2;
    private TextView tv_order_star;
    private TextView tv_order_value;
    private TextView tv_getback_mcoind;
    private TextView tv_getback_hcoind;
    private String aTokenBalnce = "";
    private String bTokenBalnce = "";


    @Override
    protected int getContentLayout() {
        return R.layout.activity_getback_coin;
    }

    @Override
    protected void initView() {
        tv_getback_mcoind = findViewById(R.id.tv_getback_mcoind);
        tv_getback_hcoind = findViewById(R.id.tv_getback_hcoind);
        scanImage = findViewById(R.id.transfer_address_scan);
        nextActionButton = findViewById(R.id.next_action_button);
        walletAddressText = findViewById(R.id.wallet_address);
        walletNameText = findViewById(R.id.wallet_name);
        balanceText = findViewById(R.id.tv_getback_mcoind);
        hmio_balance_text = findViewById(R.id.hmio_balance_text);
        feeValueText = findViewById(R.id.fee_value_text);
        mCetReceiverAddress = findViewById(R.id.cet_address);
        transferValueEdit = findViewById(R.id.transfer_value);
        transferValueEdit1 = findViewById(R.id.transfer_value_1);
        photoImage = findViewById(R.id.wallet_photo);
        titleBar = findViewById(R.id.title);
        lock_type = findViewById(R.id.lock_type);
        rl_deposit_2 = findViewById(R.id.rl_deposit_2);
        mCetReceiverAddress.findViewById(R.id.et).setEnabled(false);
        tv_order_value = findViewById(R.id.tv_order_value);
        tv_order_star = findViewById(R.id.tv_order_star);
    }

    @Override
    protected void initData() {
        aTokenBalnce = mActivity.getIntent().getStringExtra(ATOKENBALANCE);
        bTokenBalnce = mActivity.getIntent().getStringExtra(BTOKENBALANCE);
        if (!TextUtils.isEmpty(aTokenBalnce)) {
            tv_getback_mcoind.setText(aTokenBalnce + ConstantUtil.MGP_TOKEN_SYMBOL);
        }
        if (!TextUtils.isEmpty(bTokenBalnce)) {
            tv_getback_hcoind.setText(bTokenBalnce + ConstantUtil.HMIO_TOKEN_SYMBOL);
        } else {
            findViewById(R.id.rl_geback_hcoin).setVisibility(View.GONE);
        }
        NetWorkManager.getRequest().queryCurrency(BaseUrlUtils.PRICE_MGP)
                .observeOn(io.reactivex.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber2<BaseResponse<CurrencyPrice>>() {
                    @Override
                    public void onFail(String failMsg) {

                    }

                    @Override
                    public void onSuccess(BaseResponse data) {
                        try {
                            if (data.isSuccess()) {
                                CytonApplication.getInstance().MGPPrice = ((CurrencyPrice) data.getData()).getPrice().toPlainString();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
        mPresenter = new GetBackTransferPresenter(GetBackCoinActivity.this, this);
    }

    @Override
    public void updateTitleData(String title) {
        titleBar.setTitle(title);
    }

    @Override
    public void updateWalletData(Wallet wallet) {
        walletAddressText.setText(wallet.address);
        walletNameText.setText(wallet.name);
        photoImage.setImageBitmap(Blockies.createIcon(wallet.address));
    }

    @Override
    public void updaterReceiveAddress(String address) {
//        mCetReceiverAddress.setText(address);
//        isAddressOk = AddressUtil.isAddressValid(address.toString());
    }

    @Override
    public void updateAnyTokenBalance(Double balance) {
//        balanceText.setText(String.format(getString(R.string.transfer_balance_place_holder),
//                CurrencyUtil.fmtMicrometer(NumberUtil.getDecimalValid_8(balance)) + " " + mPresenter.getTokenItem().getSymbol()));
    }

    public void updateMixHTokenBalance(Double balance) {
        hmio_balance_text.setText(String.format(getString(R.string.transfer_balance_place_holder),
                CurrencyUtil.fmtMicrometer(NumberUtil.getDecimalValid_8(balance)) + " " + mPresenter.mToken1.getSymbol()));
        if (balance == null || balance.doubleValue() == 0) {
            findViewById(R.id.rl_canyu).setVisibility(View.GONE);
        }
    }

    @Override
    public void updateNativeTokenBalance(Double balance) {
    }

    @Override
    public void startUpdateEthGasPrice() {
        showProgressCircle();
    }

    @Override
    public void updateEthGasPriceSuccess(BigInteger gasPrice) {
        dismissProgressCircle();
    }

    @Override
    public void updateEthGasPriceFail(Throwable throwable) {
        Toast.makeText(mActivity, throwable.getMessage(), Toast.LENGTH_SHORT).show();
        dismissProgressCircle();
    }

    @Override
    public void initTransferFeeView() {
        feeValueText.setText(mPresenter.getTransferFee());
        initAdvancedSetup();
    }

    @Override
    public void updateCITAQuota(String quotaFee) {
        feeValueText.setText(quotaFee);
    }

    private void doNextAction() {
        getRetrieveView();
    }

    @Override
    protected void initAction() {
        scanImage.setOnClickListener((view) -> {
            AndPermission.with(mActivity)
                    .runtime().permission(Permission.Group.CAMERA)
                    .rationale(new RuntimeRationale())
                    .onGranted(permissions -> {
                        Intent intent = new Intent(mActivity, QrCodeActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    })
                    .onDenied(permissions -> PermissionUtil.showSettingDialog(mActivity, permissions))
                    .start();
        });

        nextActionButton.setOnClickListener(v -> {
            doNextAction();
        });

    }


    private void sendPushInfo(EthSendTransaction ethSendTransaction) {
        String hash = ethSendTransaction.getTransactionHash();
        String sender = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
        String receiver = walletAddressText.getText().toString().trim();
        String money = bTokenBalnce;
        String type = "8";
        String moneyType = mPresenter.getTokenItem().getSymbol();
        try {
            Map params = MapUtils.newHashMap();
            params.put("hash", hash);
            params.put("sender", sender);
            params.put("receiver", receiver);
            params.put("money", money);
            params.put("type", type);
            params.put("moneyType", moneyType);
            params.put("registrationId", CytonApplication.getInstance().registrationid);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.getTransferRecord(GetBackCoinActivity.this, content, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Estimate Gas limit when address edit text and value edit text were not null
     */
    private boolean isAddressOk = false;
    private boolean isValueOk = false;
    private boolean isValue1Ok = false;
    private boolean isNeedListen = true;

    @Override
    public void initTransferEditValue() {
        mCetReceiverAddress.setTextWatcher(new CytonTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                isAddressOk = AddressUtil.isAddressValid(s.toString());
                updateTransferEditValue();
            }
        });
//        transferValueEdit.addTextChangedListener(new CytonTextWatcher() {
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if (!isNeedListen) {
//                    return;
//                }
//                super.afterTextChanged(s);
//                try {
//                    if (!TextUtils.isEmpty(s)) {
//                        Double.parseDouble(s.toString());
//                        isValueOk = true;
//                        updateTransferEditValue();
////                            if (mPresenter.mDepositData.getType() == EntrustTransferPresenter.TYPE_LOCK_MIX && mPresenter.mBean != null) {
////                                BigDecimal mValue = new BigDecimal(s.toString());
////                                BigDecimal rateH = new BigDecimal(mPresenter.mBean.getRateH());
////                                BigDecimal rateM = new BigDecimal(mPresenter.mBean.getRateM());
////                                BigDecimal hValue = mValue.multiply(rateH).divide(rateM, 0, BigDecimal.ROUND_DOWN);
////                                isNeedListen = false;
////                                transferValueEdit1.setText(hValue.toString());
////                                isNeedListen = true;
////                            }
//                        Log.e("MainActivity", "获取 MToke的gasLimit");
//                        mPresenter.initEthGasLimit(getTransferTransaction());
//                    } else {
//                        isValueOk = false;
//                        Toast.makeText(mActivity, R.string.input_correct_value_tip, Toast.LENGTH_LONG).show();
//                    }
//                } catch (Exception e) {
//                    isValueOk = false;
//                    Toast.makeText(mActivity, R.string.input_correct_value_tip, Toast.LENGTH_LONG).show();
//                }
//            }
//        });

//        transferValueEdit1.addTextChangedListener(new
//
//                                                          CytonTextWatcher() {
//                                                              @Override
//                                                              public void afterTextChanged(Editable s) {
//                                                                  if (!isNeedListen) {
//                                                                      return;
//                                                                  }
//                                                                  super.afterTextChanged(s);
//                                                                  try {
//                                                                      if (!TextUtils.isEmpty(s)) {
//                                                                          Double.parseDouble(s.toString());
//                                                                          isValue1Ok = true;
//
//                                                                          Log.e("MainActivity", "获取 HToke的gasLimit");
//                                                                          mPresenter.initEthGasLimit(getTransferTransaction1());
//                                                                          Log.e("MainActivity", "获取 MToke的gasLimit");
//                                                                          mPresenter.initEthGasLimit(getTransferTransaction());
//                                                                      } else {
//                                                                          isValue1Ok = false;
//                                                                          Toast.makeText(mActivity, R.string.input_correct_value_tip, Toast.LENGTH_LONG).show();
//                                                                      }
//                                                                  } catch (Exception e) {
//                                                                      isValue1Ok = false;
//                                                                      Toast.makeText(mActivity, R.string.input_correct_value_tip, Toast.LENGTH_LONG).show();
//                                                                  }
//
//                                                              }
//                                                          });
    }

    private void updateTransferEditValue() {
        if (isAddressOk && isValueOk) {
            initAdvancedSetup();
//            mPresenter.initGasLimit(getTransactionInfo());
//            mPresenter.initGasLimit(getLockTransactionInfo());
        }
    }

    private void updateTransferEditValue1() {
//        if (isAddressOk && isValue1Ok) {
//            initAdvancedSetup();
//            mPresenter.initGasLimit(getTransactionInfo());
//        }
    }

//    private AppTransaction getTransactionInfo() {
//
//        AppTransaction appTransaction = new AppTransaction(mPresenter.getTokenItem().getContractAddress(), "0");
//        appTransaction.data = EthRpcService.createTokenTransferData(mCetReceiverAddress.getText(),
//                Convert.toWei(transferValueEdit.getText().toString(), Convert.Unit.ETHER).toBigInteger());
//        return appTransaction;
//    }

//    private AppTransaction getLockTransactionInfo() {
//        AppTransaction appTransaction = new AppTransaction(ConstantUtil.getDEPOSITCONTRACT(), "0");
//        if (mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_NATURE)) {
//            if (mPresenter.mDepositData.getType() != null && mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_NATURE)) {
//                appTransaction.data = EthRpcService.createLockAppandData("", null);
//            } else {
//                appTransaction.data = EthRpcService.createLockTransferData("", null);
//            }
//        } else if (mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_EMPTY)) {
//            if (mPresenter.mDepositData.getType() != null && mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_EMPTY)) {
//                appTransaction.data = EthRpcService.createLockAppandData("", null);
//
//            } else {
//                appTransaction.data = EthRpcService.createLockEmpyTransferData("", null);
//
//            }
//        } else if (mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
//            if (mPresenter.mDepositData.getType() != null && mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
//                appTransaction.data = EthRpcService.createLockAppandData("", null);
//            } else {
//                appTransaction.data = EthRpcService.createLockMixTransferData("", null);
//            }
//        }
////        appTransaction.to = ConstantUtil.DEPOSIT_CONTRACT;
//        appTransaction.value = null;
//        appTransaction.isContract = true;
////        appTransaction.data = EthRpcService.createTokenTransferData(mCetReceiverAddress.getText(),
////                Convert.toWei(transferValueEdit.getText().toString(), Convert.Unit.ETHER).toBigInteger());
//        return appTransaction;
//    }

    private void initAdvancedSetup() {
        feeValueText.setTextColor(ContextCompat.getColor(mActivity, R.color.colorPrimary));
        feeValueText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, AdvanceSetupActivity.class);
                intent.putExtra(AdvanceSetupActivity.EXTRA_TRANSFER, true);
                intent.putExtra(AdvanceSetupActivity.EXTRA_NATIVE_TOKEN, mPresenter.isNativeToken());
                mAppTransaction.chainType = mPresenter.isEther() ? ConstantUtil.TYPE_ETH : ConstantUtil.TYPE_CITA;
                mAppTransaction.data = mPresenter.getData();
                if (mPresenter.isEther()) {
                    mAppTransaction.setGasLimit(mPresenter.getmGasLimit());
                    mAppTransaction.setGasPrice(mPresenter.getGasPrice());
                    mAppTransaction.chainId = EtherUtil.getEtherId();
                } else {
                    mAppTransaction.chainId = mPresenter.getTokenItem().getChainId();
                    mAppTransaction.setQuota(mPresenter.getQuotaLimit().toString());
                }
                intent.putExtra(AdvanceSetupActivity.EXTRA_ADVANCE_SETUP, mAppTransaction);
                startActivityForResult(intent, REQUEST_CODE_TRANSACTION);
            }
        });
    }

//    private void getConfirmLockView() {
//        if (isFastDoubleClick()) return;
//        String transferValue = transferValueEdit.getText().toString().trim();
//        String transferValue1 = transferValueEdit1.getText().toString().trim();
//        String receiveAddress = mCetReceiverAddress.getText();
//        transferDialog = new TransferDialog(this, (password, progressBar) -> {
//            this.progressBar = progressBar;
//            Log.e("MainActivity", "输入密码框1");
//            transferDialog.setButtonClickAble(false);
//            progressBar.setVisibility(View.VISIBLE);
//            if (TextUtils.isEmpty(password)) {
//                transferDialog.setButtonClickAble(true);
//                progressBar.setVisibility(View.GONE);
//                Toast.makeText(mActivity, R.string.password_not_null, Toast.LENGTH_SHORT).show();
//            } else if (!WalletService.checkPassword(mActivity, password, mPresenter.getWalletItem())) {
//                transferDialog.setButtonClickAble(true);
//                progressBar.setVisibility(View.GONE);
//                Toast.makeText(mActivity, R.string.password_fail, Toast.LENGTH_SHORT).show();
//            } else {
//                Log.e("MainActivity", "输入密码框2");
//                if (mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
//                    mPresenter.handleMixLock(password, transferValue, receiveAddress);
//                } else {
//                    mPresenter.handleLock(password, transferValue, receiveAddress, mPresenter.mDepositData.getType());
//                }
//            }
//        });
//        transferDialog.confirmView.findViewById(R.id.rl_receive_address).setVisibility(View.GONE);
//        transferDialog.confirmView.findViewById(R.id.rl_pay_address).setVisibility(View.GONE);
////        transferDialog.setConfirmData(getString(R.string.commission_details), mPresenter.getWalletItem().address, receiveAddress,
////                NumberUtil.getDecimalValid_8(Double.parseDouble(transferValue)) + mPresenter.getTokenItem().getSymbol(),
////                feeValueText.getText().toString());
//        transferDialog.viewPager.setCurrentItem(1);
//    }

//    private void getConfirmTransferView() {
//        if (mPresenter.mDepositData.getCode() != 0) {
//            Toast.makeText(mActivity, R.string.get_entrust_data_fail, Toast.LENGTH_SHORT).show();
//            return;
//        }
//        if (isFastDoubleClick()) return;
//        String transferValue = transferValueEdit.getText().toString().trim();
//        String transferValue1 = transferValueEdit1.getText().toString().trim();
//        String receiveAddress = mCetReceiverAddress.getText();
//        transferDialog = new TransferDialog(this, (password, progressBar) -> {
//            this.progressBar = progressBar;
//            transferDialog.setButtonClickAble(false);
//            progressBar.setVisibility(View.VISIBLE);
//            Log.e("MainActivity", "hide progresspar");
//            if (TextUtils.isEmpty(password)) {
//                transferDialog.setButtonClickAble(true);
//                progressBar.setVisibility(View.GONE);
//                Toast.makeText(mActivity, R.string.password_not_null, Toast.LENGTH_SHORT).show();
//            } else if(mPresenter.mGasPrice == null || mPresenter.mGasPrice.compareTo(new BigInteger("-1"))==0){
//                Toast.makeText(mActivity, R.string.gas_get_fail, Toast.LENGTH_SHORT).show();
//                return;
//            }
//            else if (!WalletService.checkPassword(mActivity, password, mPresenter.getWalletItem())) {
//                transferDialog.setButtonClickAble(true);
//                progressBar.setVisibility(View.GONE);
//                Toast.makeText(mActivity, R.string.password_fail, Toast.LENGTH_SHORT).show();
//            } else {
////                transferDialog.setButtonClickAble(false);
////                progressBar.setVisibility(View.VISIBLE);
//                Log.e("MainActivity", "exec entrust");
//
//                if (mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
//                    mPresenter.handleEntrustMixTransfer(this, mPresenter.getTokenItem(), receiveAddress, transferValue, transferValue1, password);
//                } else {
//                    mPresenter.handleEntrustTransferAction(password, transferValue, receiveAddress, mPresenter.mDepositData.getType());
//                }
//            }
//        });
//        transferDialog.setConfirmData(getString(R.string.commission_details), mPresenter.getWalletItem().address, receiveAddress,
//                NumberUtil.getDecimalValid_8(Double.parseDouble(transferValue)) + mPresenter.getTokenItem().getSymbol(),
//                feeValueText.getText().toString());
//        if (mPresenter.mToken1 != null) {
//            transferDialog.setTransferValue1(NumberUtil.getDecimalValid_8(Double.parseDouble(transferValue1)) + mPresenter.mToken1.getSymbol());
//        }
//    }

    private void getRetrieveView() {
        if (isFastDoubleClick()) return;
//        if(mPresenter.mDepositData == null){
//            return;
//        }
//        BigInteger transferBalanceValue = aTokenBalnce;
//        BigInteger transferBalanceValue1 = aTokenBalnce();
        double aBalance = 0;
        double bBalance = 0;
        if (!TextUtils.isEmpty(aTokenBalnce)) {
            try {
                aBalance = Double.parseDouble(aTokenBalnce);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        if (!TextUtils.isEmpty(bTokenBalnce)) {
            try {
                bBalance = Double.parseDouble(bTokenBalnce);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        if (aBalance == 0
                && bBalance == 0) {
            Toast.makeText(mActivity, R.string.tip_no_getBack_coin, Toast.LENGTH_SHORT).show();
            return;
        }
        if (mPresenter.mGasPrice == null || mPresenter.mGasPrice.compareTo(new BigInteger("-1")) == 0) {
            Toast.makeText(mActivity, R.string.gas_get_fail, Toast.LENGTH_SHORT).show();
            return;
        }
        String receiveAddress = DBWalletUtil.getCurrentWallet(this).address;
        transferDialog = new TransferDialog(this, (password, progressBar) -> {
            this.progressBar = progressBar;
            transferDialog.setButtonClickAble(false);
            progressBar.setVisibility(View.VISIBLE);
            Log.e("MainActivity", "hide progresspar");
            if (TextUtils.isEmpty(password)) {
                transferDialog.setButtonClickAble(true);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(mActivity, R.string.password_not_null, Toast.LENGTH_SHORT).show();
            } else if (!WalletService.checkPassword(mActivity, password, mPresenter.getWalletItem())) {
                transferDialog.setButtonClickAble(true);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(mActivity, R.string.password_fail, Toast.LENGTH_SHORT).show();
            } else {
                mPresenter.handleGetBack(this, mPresenter.getTokenItem(), receiveAddress, "0", "0", password);

//                mPresenter.handleGetBack();
//                transferDialog.setButtonClickAble(false);
//                progressBar.setVisibility(View.VISIBLE);
                Log.e("MainActivity", "exec entrust");
//                if (mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
//                    mPresenter.handleEntrustMixTransfer(this, mPresenter.getTokenItem(), receiveAddress, transferValue, transferValue1, password);
//                } else {
//                    mPresenter.handleEntrustTransferAction(password, transferValue, receiveAddress, mPresenter.mDepositData.getType());
//                }
            }
        });
        String value = "";
        if (aBalance > 0) {
            value = String.valueOf(aBalance) + mPresenter.getTokenItem().getSymbol();
        }
        transferDialog.setConfirmData(getString(R.string.get_back), ConstantUtil.getDEPOSITCONTRACT(), mPresenter.getWalletItem().address,
                value,
                feeValueText.getText().toString());
//        if (mPresenter.mToken1 != null)
        if (bBalance > 0) {
            transferDialog.setTransferValue1(bBalance + ConstantUtil.HMIO_TOKEN_SYMBOL);
        }
    }

    @Override
    public void transferCITASuccess(AppSendTransaction appSendTransaction) {
        progressBar.setVisibility(View.GONE);
        if (appSendTransaction == null) {
            Toast.makeText(mActivity, R.string.transfer_fail, Toast.LENGTH_SHORT).show();
        } else if (appSendTransaction.getError() != null
                && !TextUtils.isEmpty(appSendTransaction.getError().getMessage())) {
            Toast.makeText(mActivity, appSendTransaction.getError().getMessage(),
                    Toast.LENGTH_SHORT).show();
        } else if (!TextUtils.isEmpty(appSendTransaction.getSendTransactionResult().getHash())) {
            Toast.makeText(GetBackCoinActivity.this, R.string.transfer_success, Toast.LENGTH_SHORT).show();
            transferDialog.dismiss();
            EventBus.getDefault().post(new TransferPushEvent());
            finish();
        } else {
            Toast.makeText(mActivity, R.string.transfer_fail, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void transferCITAFail(Throwable e) {
        progressBar.setVisibility(View.GONE);
        Toast.makeText(GetBackCoinActivity.this,
                e.getMessage(), Toast.LENGTH_SHORT).show();
        transferDialog.dismiss();
    }

//    public void updateLockStatus() {
//        if (mPresenter.mDepositData.getStep() == EntrustNewTransferPresenter.TYPE_CURRENT_STEP_TRANSFER) {
//            if (mPresenter.mDepositData.isAppend()) {
//                nextActionButton.button.setText(getString(R.string.append_initiate));
//            } else {
//                nextActionButton.button.setText(getString(R.string.authorization));
//            }
//
//            if (mPresenter.mDepositData.getType() != null
//                    && mPresenter.mDepositData.getType().equals(TYPE_LOCK_MIX)
//                    && mPresenter.mToken1 != null) {
//                mPresenter.initEthGasLimit(getTransferTransaction());
//            } else {
//                mPresenter.initEthGasLimit(getTransferTransaction());
//            }
//        } else {
//            findViewById(R.id.rl_canyu).setVisibility(View.GONE);
//
//            isNeedListen = false;
//            if (mPresenter.mDepositData.isAppend()) {
//                nextActionButton.button.setText(getString(R.string.append));
//            } else {
//                nextActionButton.button.setText(getString(R.string.Deposit_confirm));
//            }
//
//            if (mPresenter.mDepositData.getType().equals(TYPE_LOCK_NATURE)) {
//                if (mPresenter.mDepositData.getaTokenBalance().compareTo(BigInteger.ZERO) > 0) {
//                    transferValueEdit.setText("" + NumberUtil.getEthFromWei(mPresenter.mDepositData.getaTokenBalance()));
//                } else if (mPresenter.mDepositData.getaPendingBalance().compareTo(BigInteger.ZERO) > 0) {
//                    transferValueEdit.setText("" + NumberUtil.getEthFromWei(mPresenter.mDepositData.getaPendingBalance()));
//                }
//            } else if (mPresenter.mDepositData.getType().equals(EntrustNewTransferPresenter.TYPE_LOCK_EMPTY)) {
//                if (mPresenter.mDepositData.getbTokenBalance().compareTo(BigInteger.ZERO) > 0) {
//                    transferValueEdit.setText("" + NumberUtil.getEthFromWei(mPresenter.mDepositData.getbTokenBalance()));
//                } else if (mPresenter.mDepositData.getbPendingBalance().compareTo(BigInteger.ZERO) > 0) {
//                    transferValueEdit.setText("" + NumberUtil.getEthFromWei(mPresenter.mDepositData.getbPendingBalance()));
//                }
//            } else if (mPresenter.mDepositData.getType().equals(TYPE_LOCK_MIX)) {
//                if (mPresenter.mDepositData.getaTokenBalance().compareTo(BigInteger.ZERO) > 0) {
//                    transferValueEdit.setText("" + NumberUtil.getEthFromWei(mPresenter.mDepositData.getaTokenBalance()));
//                } else if (mPresenter.mDepositData.getaPendingBalance().compareTo(BigInteger.ZERO) > 0) {
//                    transferValueEdit.setText("" + NumberUtil.getEthFromWei(mPresenter.mDepositData.getaPendingBalance()));
//                }
//
//                if (mPresenter.mDepositData.getbTokenBalance().compareTo(BigInteger.ZERO) > 0) {
//                    transferValueEdit1.setText("" + NumberUtil.getEthFromWei(mPresenter.mDepositData.getbTokenBalance()));
//                } else if (mPresenter.mDepositData.getbPendingBalance().compareTo(BigInteger.ZERO) > 0) {
//                    transferValueEdit1.setText("" + NumberUtil.getEthFromWei(mPresenter.mDepositData.getbPendingBalance()));
//                }
//
//
//            }
//            transferValueEdit.setEnabled(false);
//            transferValueEdit1.setEnabled(false);
//            mPresenter.initEthGasLimit(getLockTransaction());
//        }
//        String MGPPrice = CytonApplication.getInstance().MGPPrice;
//        String mCoinAmount = transferValueEdit.getText().toString();
//        String hCoinAmount = transferValueEdit1.getText().toString();
//        if (mPresenter.mDepositData.isAppend()) {
//            findViewById(R.id.rl_canyu).setVisibility(View.GONE);
////                    String MGPPrice = CytonApplication.getInstance().MGPPrice;
//            if (!TextUtils.isEmpty(MGPPrice)) {
//                BigDecimal value = new BigDecimal(mPresenter.mDepositData.getLockNum());
//                BigDecimal amount = value.multiply(new BigDecimal(MGPPrice)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
//                tv_order_value.setText("$" + amount.toString());
//                if (amount.compareTo(new BigDecimal("10000")) >= 0) {
//                    tv_order_star.setText("M4");
//                } else if (amount.compareTo(new BigDecimal("5000")) >= 0) {
//                    tv_order_star.setText("M3");
//                } else if (amount.compareTo(new BigDecimal("2000")) >= 0) {
//                    tv_order_star.setText("M2");
//                } else if (amount.compareTo(new BigDecimal("500")) >= 0) {
//                    tv_order_star.setText("M1");
//                } else {
//                    tv_order_star.setText("M0");
//                }
//            }
//        } else if (!TextUtils.isEmpty(MGPPrice) && !TextUtils.isEmpty(mCoinAmount)) {
//            BigDecimal value = new BigDecimal(mCoinAmount);
//            if (!TextUtils.isEmpty(hCoinAmount)) {
//                value = value.add(new BigDecimal(hCoinAmount));
//            }
//            BigDecimal amount = value.multiply(new BigDecimal(MGPPrice)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
//            tv_order_value.setText("$" + amount.toString());
//
//            if (amount.compareTo(new BigDecimal("10000")) >= 0) {
//                tv_order_star.setText("M4");
//            } else if (amount.compareTo(new BigDecimal("5000")) >= 0) {
//                tv_order_star.setText("M3");
//            } else if (amount.compareTo(new BigDecimal("2000")) >= 0) {
//                tv_order_star.setText("M2");
//            } else if (amount.compareTo(new BigDecimal("500")) >= 0) {
//                tv_order_star.setText("M1");
//            } else {
//                tv_order_star.setText("M0");
//            }
//        }
//    }

    public org.web3j.protocol.core.methods.request.Transaction getTransactionInfo() {
        String address = DBWalletUtil.getCurrentWallet(this).address;
        String data = EthRpcService.createClaimTransferData(null, null);
        org.web3j.protocol.core.methods.request.Transaction transaction = org.web3j.protocol.core.methods.request.Transaction.
                createFunctionCallTransaction(address, null, null, null, ConstantUtil.getDEPOSITCONTRACT(), data);
        return transaction;
    }

//    public Transaction getTransferTransaction() {
//        String address = DBWalletUtil.getCurrentWallet(this).address;
//        String data = EthRpcService.createTokenTransferData(mCetReceiverAddress.getText(),
//                Convert.toWei("1000"/*transferValueEdit.getText().toString()*/, Convert.Unit.ETHER).toBigInteger());
//        Transaction transaction = org.web3j.protocol.core.methods.request.Transaction.
//                createFunctionCallTransaction(address, null, null, null, mPresenter.getTokenItem().getContractAddress(), data);
//        return transaction;
//    }

    public Transaction getTransferTransaction1() {
        String address = DBWalletUtil.getCurrentWallet(this).address;
        String data = EthRpcService.createTokenTransferData(mCetReceiverAddress.getText(),
                Convert.toWei("0"/*transferValueEdit1.getText().toString()*/, Convert.Unit.ETHER).toBigInteger());
        Transaction transaction = org.web3j.protocol.core.methods.request.Transaction.
                createFunctionCallTransaction(address, null, null, null, mPresenter.mToken1.getContractAddress(), data);
        return transaction;
    }

//    public Transaction getLockTransaction() {
//        String address = DBWalletUtil.getCurrentWallet(this).address;
//        String data = "";
//        if (mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_NATURE)) {
//            if (mPresenter.mDepositData.isAppend()) {
//                data = EthRpcService.createLockAppandData("", null);
//            } else {
//                data = EthRpcService.createLockTransferData("", null);
//            }
//        } else if (mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_EMPTY)) {
//            if (mPresenter.mDepositData.isAppend()) {
//                data = EthRpcService.createLockAppandData("", null);
//            } else {
//                data = EthRpcService.createLockEmpyTransferData("", null);
//            }
//        } else if (mPresenter.mDepositData.getType().equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
//            if (mPresenter.mDepositData.isAppend()) {
//                data = EthRpcService.createLockAppandData("", null);
//            } else {
//                data = EthRpcService.createLockMixTransferData("", null);
//            }
//        }
//        Transaction transaction = org.web3j.protocol.core.methods.request.Transaction.
//                createFunctionCallTransaction(address, null, null, null, ConstantUtil.getDEPOSITCONTRACT(), data);
//        return transaction;
//    }

    @Override
    public void transferEtherSuccess(EthSendTransaction ethSendTransaction) {
        progressBar.setVisibility(View.GONE);
        if (ethSendTransaction == null) {
            Toast.makeText(mActivity, R.string.transfer_fail, Toast.LENGTH_SHORT).show();
        } else if (ethSendTransaction.getError() != null
                && !TextUtils.isEmpty(ethSendTransaction.getError().getMessage())) {
            Toast.makeText(mActivity, ethSendTransaction.getError().getMessage(),
                    Toast.LENGTH_SHORT).show();
        } else if (!TextUtils.isEmpty(ethSendTransaction.getTransactionHash())) {
            sendPushInfo(ethSendTransaction);
            Toast.makeText(mActivity, R.string.transfer_success, Toast.LENGTH_SHORT).show();
            transferDialog.dismiss();
            finish();
//
//            if (mPresenter.mDepositData.getStep() == EntrustNewTransferPresenter.TYPE_CURRENT_STEP_TRANSFER) {
//                if (mPresenter.mDepositData.isAppend()) {
//                    Toast.makeText(mActivity, R.string.tip_append_start, Toast.LENGTH_SHORT).show();
//
//                } else {
//                    Toast.makeText(mActivity, R.string.tip_mortgage_start, Toast.LENGTH_SHORT).show();
//                }
//            } else {
//                if (mPresenter.mDepositData.isAppend()) {
//                    Toast.makeText(mActivity, R.string.tip_append_end, Toast.LENGTH_SHORT).show();
//
//                } else {
//                    Toast.makeText(mActivity, R.string.tip_mortgage_end, Toast.LENGTH_SHORT).show();
//                }
//            }

//            EventBus.getDefault().post(new TransferPushEvent());
//            finish();
        } else {
            Toast.makeText(mActivity, R.string.transfer_fail, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void transferEtherFail(String message) {
        progressBar.setVisibility(View.GONE);
        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
        transferDialog.dismiss();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (transferDialog != null) {
            transferDialog.dismiss();
        }
        EthRpcService.mNonce = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SCAN:
                if (null == data) return;
                Bundle bundle = data.getExtras();
                if (bundle == null) return;
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    switch (bundle.getInt(CodeUtils.STRING_TYPE)) {
                        case com.cryptape.cita_wallet.util.qrcode.CodeUtils.STRING_ADDRESS:
                            String result = bundle.getString(CodeUtils.RESULT_STRING);
                            mCetReceiverAddress.setText(result);
                            break;
                        default:
                            Toast.makeText(this, R.string.address_error,
                                    Toast.LENGTH_LONG).show();
                            break;
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(GetBackCoinActivity.this, R.string.qrcode_handle_fail,
                            Toast.LENGTH_LONG).show();
                }
                break;
            case REQUEST_CODE_TRANSACTION:
                switch (resultCode) {
                    case AdvanceSetupActivity.RESULT_TRANSACTION:
                        mAppTransaction = data.getParcelableExtra(AdvanceSetupActivity.EXTRA_TRANSACTION);
                        mPresenter.updateData(mAppTransaction.data);
                        if (mAppTransaction.isEthereum()) {
                            mPresenter.updateGasLimit(mAppTransaction.getGasLimit());
                            mPresenter.updateGasPrice(mAppTransaction.getGasPrice());
                        } else {
                            mPresenter.updateQuotaLimit(mAppTransaction.getQuota());
                        }
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }
}
